#include "music.h"

#include <QUuid>
#include <QMediaPlayer>
#include <QAudioOutput>
#include <QMediaMetaData>
#include <QVariantMap>
#include <QVariant>
#include <QDebug>
#include <QSqlError>
#include <QCoreApplication>

Music::Music()
    : isLike(false)
    , isHistroy(false)
    , isSearched(false)
{
    musicId = QUuid::createUuid().toString();
    parse();
}

Music::Music(QUrl url)
    : isLike(false)
    , isHistroy(false)
    , musicUrl(url)
    , isSearched(false)
{
    //解析路径信息
    qDebug() << "MusicUrl in Music" << musicUrl;
    musicId = QUuid::createUuid().toString();
    parse();
}

void Music::setMusicId(QString musicId)
{
    this->musicId = musicId;
}

void Music::setMusicName(const QString& name)
{
    musicName = name;
}

void Music::setMusicSinger(const QString& singer)
{
    musicSinger = singer;
}

void Music::setMusicAlbum(const QString& album)
{
    musicAlbum = album;
}

void Music::setMusicDuration(qint64 duration)
{
    this->duration = duration;
}

void Music::setIsLike(bool islike)
{
    this->isLike = islike;
}

void Music::setIsHistory(bool ishistroy)
{
    this->isHistroy = ishistroy;
}

void Music::setMusicUrl(QUrl url)
{
    this->musicUrl = url;
}

void Music::setDuration(int duration)
{
    this->duration = duration;
}

void Music::setMusicCover(QVariant musicCover)
{
    this->musicCover = musicCover;
}

////////////////////

const QString& Music::getMusicName() const
{
    return musicName;
}

const QString& Music::getMusicSinger() const
{
    return musicSinger;
}

const QString& Music::getMusicAlbum() const
{
    return musicAlbum;
}

qint64 Music::getMusicDuration() const
{
    return duration;
}

bool Music::getIsLike() const
{
    return isLike;
}

bool Music::getIsHistory() const
{
    return isHistroy;
}

const QUrl& Music::getMusicUrl() const
{
    return musicUrl;
}

const QString &Music::getMusicId() const
{
    return musicId;
}

const QVariant &Music::getMusicCover()
{
    return musicCover;
}

QString Music::getLrcFilePath()
{
    QString lrcFilePath = musicUrl.toLocalFile();
    qDebug() << musicUrl.toLocalFile();
    qDebug() << lrcFilePath;

    lrcFilePath.replace(".mp3", ".lrc");

    qDebug() << lrcFilePath;

    return lrcFilePath;
}

bool Music::getIsSearched()
{
    return isSearched;
}

void Music::setIsSearched(bool isSearched)
{
    this->isSearched = isSearched;
}

void Music::writeMusicInfo()
{
    QSqlQuery query;

    query.prepare("SELECT EXISTS (SELECT 1 FROM musicInfo WHERE musicId = ?)");
    query.addBindValue(musicId);
    if(!query.exec())
    {
        qDebug() << "select musicInfo fail========" << query.lastError().text();
        return;
    }

    if(query.next())
    {
        bool isExists = query.value(0).toBool();
        if(isExists)
        {
            //如果已经存在，只需要更新最近播放和喜欢即可
            query.prepare("UPDATE musicInfo SET isLike = ?, isHistory = ? WHERE musicId = ?");
            query.addBindValue(isLike ? 1 : 0);
            query.addBindValue(isHistroy ? 1 : 0);
            query.addBindValue(musicId);
            if(!query.exec())
            {
                qDebug() << "更新musicInfo失败" << query.lastError().text();
                return;
            }
            qDebug() << "更新成功";
        }
        else if(!isExists)
        {
            query.prepare("insert into musicInfo values\
                        (:musicId, :musicName, :musicSinger, :musicAlbum, \
                          :duration, :isLike, :isHistroy, :musicUrl);");
            query.bindValue(":musicId", musicId);
            query.bindValue(":musicName", musicName);
            query.bindValue(":musicSinger", musicSinger);                        query.bindValue(":musicAlbum", musicAlbum);
            query.bindValue(":duration", duration);
            query.bindValue(":isLike", isLike ? 1 : 0);
            query.bindValue(":isHistroy", isHistroy ? 1 : 0);
            //query.bindValue(":musicUrl", musicUrl.toLocalFile());
            query.bindValue(":musicUrl", musicUrl);
            if(!query.exec())
            {
                qDebug() << "insert into musicInfoDB fail" << query.lastError().text();
                qDebug() << "=========";
                return;
            }
            qDebug() << "insert into musicInfoDB success";
            qDebug() << "=========";
        }
    }
}

void Music::parse()
{
    QMediaPlayer player;
    player.setSource(musicUrl);

    while(player.mediaStatus() != QMediaPlayer::LoadedMedia)
    {
        QCoreApplication::processEvents(); //等待多媒体文件加载完成时继续进行消息队列的循环
    }

    if(player.mediaStatus() == QMediaPlayer::LoadedMedia)
    {
        //处理歌曲相关文本信息
        QMediaMetaData data = player.metaData();
        musicName = data[QMediaMetaData::Title].toString();
        musicSinger = data[QMediaMetaData::Author].toString();
        musicAlbum = data[QMediaMetaData::AlbumTitle].toString();
        duration = data[QMediaMetaData::Duration].toLongLong();
        musicCover = data[QMediaMetaData::ThumbnailImage];

        QString filename = musicUrl.fileName();
        if(musicName.isEmpty())
        {
            int index = filename.indexOf("-");
            if(index != -1)
            {
                musicName = filename.mid(0, index);
            }
            else
            {
                musicName = "未知歌名";
            }
        }
        if(musicSinger.isEmpty())
        {
            int index1 = filename.indexOf("-");
            if(index1 != -1)
            {
                musicSinger = filename.mid(index1 + 1);
                int index2 = musicSinger.indexOf(".");
                musicSinger = musicSinger.mid(0, index2);
            }
            else
                musicSinger = "未知歌手";
        }
        if(musicAlbum.isEmpty())
        {
            musicAlbum = "未知专辑";
        }
    }
}


